/**
 * 
 */
package nl.sportan.samenloop.adapter;

import nl.sportan.samenloop.R;
import nl.sportan.samenloop.communication.PhotoTarget;
import nl.sportan.samenloop.communication.flickr.PhotoDataRetriever;
import android.content.Context;
import android.graphics.Bitmap;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.gmail.yuyang226.flickr.photos.Photo;
import com.gmail.yuyang226.flickr.photos.PhotoList;
import com.gmail.yuyang226.flickr.photos.Size;

/**
 * @author Bram Wiekens
 *
 */
public class PhotoAdapter extends BaseAdapter {

	private PhotoList photoList;
	private Context context;
	private Handler handler;
	
	public PhotoAdapter(Context ctx, PhotoList photoList) {
		this.context = ctx;
		this.handler = new Handler();
		this.photoList = photoList;
	}
	
	public int getCount() {
		return photoList.getTotal();
	}

	public Object getItem(int position) {
		return photoList.get(position);
	}

	public long getItemId(int position) {
		return position;
	}

	public View getView(int position, View convertView, ViewGroup parent) {
			Photo ps = photoList.get(position);
			
			String title = ps.getTitle();
			
			RelativeLayout imageLayout;

			imageLayout = (RelativeLayout) LayoutInflater.from(context).inflate(
					R.layout.flickr_short, parent, false);
			
			TextView titleView = (TextView) imageLayout.findViewById(R.id.title);
			titleView.setText(title);
			
			ImageView iv = (ImageView) imageLayout.findViewById(R.id.image);
			// FIXME This is wrong, very wrong!! Change to Thread workers!
			Thread t = new Thread(new PhotoDataRetriever(context, ps, Size.SQUARE, new PhotoHolder(iv) , true));
			t.start();
			
			return imageLayout;
		}
		
		private class PhotoHolder implements PhotoTarget {

			private ImageView target;
			
			public PhotoHolder(ImageView target ) {
				this.target = target;
			}
			
			public void setPhoto(Bitmap bitmap) {
				handler.post(new PhotoUpdater(bitmap, target));			
			}
			
		}
		
		
		private class PhotoUpdater implements Runnable {

			private Bitmap bitmap;
			private ImageView target;
			
			public PhotoUpdater(Bitmap bitmap, ImageView target) {
				this.bitmap = bitmap;
				this.target = target;
			}
			
			public void run() {
				target.setImageBitmap(bitmap);
			}

			
		}


}
